package com.yami.shop.platform.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yami.shop.bean.dto.UltraGroupAutoRenewDTO;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.event.SendMessageEvent;
import com.yami.shop.bean.event.SendPersonMessageEvent;
import com.yami.shop.bean.model.MeltCloudGroup;
import com.yami.shop.bean.model.MeltCloudUltraGroupRecord;
import com.yami.shop.bean.param.NotifyTemplateParam;
import com.yami.shop.common.config.Constant;
import com.yami.shop.service.*;
import com.yami.shop.user.common.service.UserGasInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
@AllArgsConstructor
public class UltraGroupTask {
    
    private final MeltCloudUltraGroupCostService ultraGroupCostService;
    
    private final MeltCloudUltraGroupRecordService ultraGroupRecordService;
    
    private final MeltCloudGroupService groupService;

    private final ShopDetailService shopDetailService;

    private final UserGasInfoService userGasInfoService;

    private final ApplicationContext applicationContext;


    /**
     * 超级群聊到期 
     * 每天00:00:00执行一次
     */
    @XxlJob("ultraGroupExpires")
    public void ultraGroupExpires() {
        DateTime day = DateUtil.beginOfDay(DateUtil.date());
        List<MeltCloudGroup> list = groupService.list(Wrappers.lambdaQuery(MeltCloudGroup.class)
                .eq(MeltCloudGroup::getType, "1").eq(MeltCloudGroup::getIsArrears, 0).and(wp -> wp.isNull(MeltCloudGroup::getShopId).or().ne(MeltCloudGroup::getShopId, 0)).le(MeltCloudGroup::getExpirationTime, day));
        if (CollUtil.isNotEmpty(list)) {
            Set<Long> groupIds = list.stream().map(MeltCloudGroup::getId).collect(Collectors.toSet());
            groupService.update(Wrappers.lambdaUpdate(MeltCloudGroup.class).set(MeltCloudGroup::getIsArrears, 1).in(MeltCloudGroup::getId, groupIds));
            log.info("====== " + groupIds.size() + "个超级群已到期欠费！======");
        } else {
            log.info("====== 无到期超级群！======");
        }
    }
    
    
    /**
     * 超级群聊自动续费
     * 到期前一天执行
     * 每天00:00:00执行一次
     */
    @XxlJob("ultraGroupAutoRenewal")
    public void ultraGroupAutoRenewal() {
        List<UltraGroupAutoRenewDTO> list = ultraGroupCostService.getAutoRenewUltraGroup();
        if (CollUtil.isEmpty(list)) {
            log.info("===无需要自动续费的超级群聊===");
            return;
        }
        log.info("======{}个超级群进入自动续费======", list.size());
        List<MeltCloudGroup> groups = new ArrayList<>();
        List<MeltCloudUltraGroupRecord> records = new ArrayList<>();
        for (UltraGroupAutoRenewDTO dto : list) {
            String result = "true";
            if (Objects.isNull(dto.getShopId())) {
                // 用户
                try{
                    userGasInfoService.reduceGasNumberByUserId(dto.getCreatorUserId(), dto.getRenewValue());
                } catch (Exception e) {
                    result = e.getMessage();
                }
            } else {
                result = shopDetailService.consumptionGasByShopId(dto.getShopId(), dto.getRenewValue());
            }
            if (result.equals("true")) {
                DateTime dateTime = DateUtil.offsetMonth(dto.getExpirationTime(), 1);
                MeltCloudGroup group = MeltCloudGroup.builder().id(dto.getGroupId()).expirationTime(dateTime).build();
                groups.add(group);
                log.info("超级群聊ID：{}，续费成功！", dto.getGroupId());
            } else {
                log.error("超级群聊ID：{}，续费失败：{}", dto.getGroupId(), result);
                String msg = result.length() > 500 ? result.substring(0, 500) : result;
                MeltCloudUltraGroupRecord record = MeltCloudUltraGroupRecord.builder().groupApplyId(dto.getApplyId()).status(3).reason(msg).build();
                records.add(record);
            }
        }
        if (CollUtil.isNotEmpty(groups)) {
            groupService.updateBatchById(groups);
            log.info("超级群聊自动续费成功{}个", groups.size());
        }
        if (CollUtil.isNotEmpty(records)) {
            ultraGroupRecordService.saveBatch(records);
            log.error("超级群聊自动续费失败{}个", records.size());
        }
    }


    /**
     * 每天早上9点执行一次
     */
    @XxlJob("ultraGroupExpiresNotice")
    public void ultraGroupExpiresNotice() {
        log.info("==================超级群到期前2天消息提示=================");
        List<MeltCloudGroup> list = groupService.dueSoonUltraGroup();
        if (CollUtil.isEmpty(list)) {
            log.info("==================无将要到期的超级群=================");
            return;
        }
        log.info("=================={}个超级群将到期=================", list.size());
        String date = DateUtil.format(list.get(0).getExpirationTime(), DatePattern.CHINESE_DATE_PATTERN);
        List<MeltCloudGroup> shopList = list.stream().filter(g -> g.getCreatorUserId().startsWith("shop_") && Objects.nonNull(g.getShopId())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(shopList)) {
            Map<Long, List<MeltCloudGroup>> shopListMap = shopList.stream().collect(Collectors.groupingBy(MeltCloudGroup::getShopId));
            shopListMap.forEach((shopId, groups) -> {
                String groupNames = groups.stream().map(MeltCloudGroup::getGroupName).collect(Collectors.joining("、"));
                NotifyTemplateParam shopParam = new NotifyTemplateParam();
                shopParam.setShopId(Constant.PLATFORM_SHOP_ID);
                shopParam.setSendType(SendType.ULTRA_GROUP_EXPIRATION_SHOP.getValue());
                shopParam.setShopId(shopId);
                shopParam.setActivityName(groupNames);
                shopParam.setCancelTime(date);
                applicationContext.publishEvent(new SendMessageEvent(shopParam));
                log.info("========已通知群主(商家)：{}，超级群：{}即将到期=========", shopId, groupNames);
            });
            log.info("==================商户端：{}个超级群即将到期，已通知到{}位商户端群主=================", shopList.size(), shopListMap.size());
        }
        
        List<MeltCloudGroup> userList = list.stream().filter(g -> !g.getCreatorUserId().startsWith("plat_") && !g.getCreatorUserId().startsWith("shop_")).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(userList)) {
            Map<String, List<MeltCloudGroup>> userListMap = userList.stream().collect(Collectors.groupingBy(MeltCloudGroup::getCreatorUserId));
            userListMap.forEach((userId, groups) -> {
                String groupNames = groups.stream().map(MeltCloudGroup::getGroupName).collect(Collectors.joining("、"));
                NotifyTemplateParam shopParam = new NotifyTemplateParam();
                shopParam.setShopId(Constant.PLATFORM_SHOP_ID);
                shopParam.setSendType(SendType.ULTRA_GROUP_EXPIRATION.getValue());
                shopParam.setUserId(userId);
                shopParam.setContent(groupNames);
                shopParam.setTitle(date);
                applicationContext.publishEvent(new SendPersonMessageEvent(shopParam));
                log.info("========已通知群主(c端)：{}，超级群：{}即将到期=========", userId, groupNames);
            });
            log.info("==================移动端：{}个超级群即将到期，已通知到{}位c端群主=================", userList.size(), userListMap.size());
        }
    }
    
    
    
}
